<template>
    <div class="policy-header">
      <h1>政策/协议</h1>
      <div class="header-selection">
        <select v-model="typeFilter" class="filter-select" @change="fetchAgreements">
          <option value="">全部类型</option>
          <option value="PP">微信-隐私政策</option>
          <option value="UA">微信-用户协议</option>
          <option value="AD_PP">安卓-隐私政策</option>
          <option value="AD_UA">安卓-用户协议</option>
        </select>
        <select v-model="enabledFilter" class="filter-select" @change="fetchAgreements">
          <option value="">全部状态</option>
          <option value="1">启用</option>
          <option value="0">禁用</option>
        </select>
      </div>
      <div class="header-actions">
        <button class="refresh-btn" @click="fetchAgreements(false)">
          刷新
        </button>
        <button class="new-btn" @click="openAddDialog()">
          新增
        </button>
      </div>
    </div>
    
    <div class="policy-list-content">
      <!-- 协议列表 -->
      <div class="agreement-list">
        <div v-if="loading && agreements.length === 0" class="loading-state">
          加载中...
        </div>
        
        <div v-else-if="agreements.length === 0" class="empty-state">
          暂无协议数据
        </div>
        
        <div v-else class="agreement-items">
          <div v-for="agreement in agreements" :key="agreement.id" class="agreement-item">
            <div class="agreement-header">
              <div class="agreement-title">
                <span class="agreement-type">{{ agreement.type === 'PP' ? '隐私政策' : '用户协议' }}</span>
                <span class="agreement-version">版本 {{ agreement.ver }}</span>
              </div>
              <div class="agreement-meta">
                <button 
                  :class="['status-badge', agreement.enabled? 'enabled' : 'disabled']"
                  @click="toggleAgreementStatus(agreement)"
                >
                  {{ agreement.enabled? '启用' : '禁用' }}
                </button>
                <button class="view-btn" @click="showContent(agreement)">查看详情</button>
                <button class="update-btn" @click="openUpdateDialog(agreement, false)">
                  更新
                </button>
                <button class="new-version-btn" @click="openUpdateDialog(agreement, true)">
                  新版本
                </button>
              </div>
            </div>
            <div class="agreement-info">
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ agreement.createdAt }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建人：</span>
                <span class="value">{{ agreement.createdBy }}</span>
              </div>
              <div class="info-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ agreement.updatedAt }}</span>
              </div>
            </div>
            <div class="agreement-preview">
              {{ truncateContent(agreement.content) }}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多指示器 -->
      <div v-if="loading && agreements.length > 0" class="loading-more">
        <div class="loading-spinner-small"></div>
        <span>加载更多...</span>
      </div>
      
      <!-- 已加载全部数据提示 -->
      <div v-if="!hasMore && agreements.length > 0" class="load-complete">
        已加载全部数据
      </div>
    </div>
    
    <!-- 详情弹窗 -->
    <div v-if="showDetail" class="detail-modal" @click="closeDetail">
      <div class="detail-content" @click.stop>
        <div class="detail-header">
          <h2>{{ selectedAgreement?.type === 'PP' ? '隐私政策' : '用户协议' }} - 版本 {{ selectedAgreement?.ver }}</h2>
          <button class="close-btn" @click="closeDetail">×</button>
        </div>
        <div class="detail-body">
          <div class="detail-info">
            <div class="info-row">
              <span class="info-label">ID：</span>
              <span class="info-value">{{ selectedAgreement?.id }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">状态：</span>
              <span :class="['info-status', selectedAgreement?.enabled? 'enabled' : 'disabled']">
                {{ selectedAgreement?.enabled? '启用' : '禁用' }}
              </span>
            </div>
            <div class="info-row">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ selectedAgreement?.createdAt }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">创建人：</span>
              <span class="info-value">{{ selectedAgreement?.createdBy }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">更新时间：</span>
              <span class="info-value">{{ selectedAgreement?.updatedAt }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">更新人：</span>
              <span class="info-value">{{ selectedAgreement?.updatedBy }}</span>
            </div>
          </div>
          <div class="detail-text">
            <h3>内容详情</h3>
            <div class="content-display">
              {{ selectedAgreement?.content || '暂无内容' }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 更新对话框 -->
    <div v-if="showUpdateDialog" class="detail-modal" @click="closeUpdateDialog">
      <div class="detail-content" @click.stop>
        <div class="detail-header">
          <h2>{{ isNewVersion ? '创建新版本' : '更新协议' }}</h2>
          <button class="close-btn" @click="closeUpdateDialog">×</button>
        </div>
        <div class="detail-body">
          <div class="update-form">
            <div class="form-group">
          <label>协议类型</label>
          <template v-if="isAdding">
            <select v-model="editingAgreement.type" class="filter-select">
              <option value="">请选择协议类型</option>
              <option value="PP">隐私政策</option>
              <option value="UA">用户协议</option>
            </select>
          </template>
          <input v-else type="text" v-model="editingAgreement.type" disabled>
        </div>
            <div class="form-group">
              <label>当前版本</label>
              <input type="text" :value="`v${editingAgreement.ver}`" disabled>
            </div>
            <div class="form-group">
              <label>协议内容</label>
              <textarea v-model="editingAgreement.content" :disabled="isLoadingContent" rows="10"></textarea>
            </div>
            <div class="form-actions">
              <button class="cancel-btn" @click="closeUpdateDialog" :disabled="isSaving">取消</button>
              <button class="save-btn" @click="saveAgreement" :disabled="isSaving">
                <span v-if="isSaving">保存中...</span>
                <span v-else>保存</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { invoke } from '@tauri-apps/api/core'

// 定义协议接口
interface Agreement {
  id: string;
  type: string;
  content: string;
  ver: number;
  enabled: number;
  createdAt: string;
  createdBy: string;
  updatedAt: string;
  updatedBy: string;
}

// 定义分页响应接口
interface PaginationResponse {
  records: Agreement[];
  total: number;
  size: number;
  current: number;
  orders: [];
  optimizeCountSql: boolean;
  hitCount: boolean;
  searchCount: boolean;
  pages: number;
}

// 定义API响应接口
export interface ApiResponse {
  code: number;
  status: number;
  msg: string;
  data: PaginationResponse;
}

// 数据状态
const agreements = ref<Agreement[]>([]);
const loading = ref(false);
const selectedAgreement = ref<Agreement | null>(null);
const showDetail = ref(false);
const updatingStatus = ref<string[]>([]); // 记录正在更新状态的协议ID

// 更新对话框相关状态
const showUpdateDialog = ref(false);
const editingAgreement = ref<Agreement>({
  id: '',
  type: '',
  content: '',
  ver: 0,
  enabled: 0,
  createdAt: '',
  createdBy: '',
  updatedAt: '',
  updatedBy: ''
});
const isNewVersion = ref(false);
const isAdding = ref(false);
const isLoadingContent = ref(false);
const isSaving = ref(false);

// 分页参数
const pageNum = ref(1);
const pageSize = ref(20); // 增加每页显示数量
const total = ref(0);
const hasMore = ref(true);
const loadingMore = ref(false);

// 筛选参数
const typeFilter = ref('');
const enabledFilter = ref('');

// 上一次的筛选条件，用于检测变化
const lastFilters = ref({
  type: '',
  enabled: ''
});

// 防抖函数
const debounce = <T extends (...args: any[]) => any>(func: T, wait: number): T => {
  let timeout: ReturnType<typeof setTimeout> | null = null;
  return function(this: any, ...args: Parameters<T>) {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  } as T;
};

// 获取协议列表
const fetchAgreements = async (isLoadMore: boolean = false) => {
  console.log('fetchAgreements called:', { isLoadMore, typeFilter: typeFilter.value, enabledFilter: enabledFilter.value });
  
  // 检查筛选条件是否发生变化
  const filtersChanged = 
    typeFilter.value !== lastFilters.value.type || 
    enabledFilter.value !== lastFilters.value.enabled;
  
  // 如果筛选条件变化，强制重置为非加载更多模式
  if (filtersChanged && isLoadMore) {
    console.log('Filters changed, switching to full refresh instead of load more');
    isLoadMore = false;
  }
  
  if (loading.value || (isLoadMore && loadingMore.value)) {
    console.log('fetchAgreements skipped - already loading');
    return;
  }
  
  if (isLoadMore) {
    loadingMore.value = true;
  } else {
    loading.value = true;
    // 重置数据 - 当查询条件变化时，清空已有数据重新加载
    agreements.value = [];
    pageNum.value = 1;
    hasMore.value = true;
    
    // 更新上次筛选条件记录
    lastFilters.value = {
      type: typeFilter.value,
      enabled: enabledFilter.value
    };
    console.log('Filters updated and data reset for new query');
  }
  
  try {
    // 通过Tauri调用Rust的API - 使用驼峰形式参数名
    const responseStr = await invoke<string>('get_agreements', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      typeFilter: typeFilter.value,
      enabledFilter: enabledFilter.value
    });
    
    // 处理响应数据
    const apiResponse: ApiResponse = JSON.parse(responseStr);
    console.log('API Response:', apiResponse);
    
    if (apiResponse.code === 200 && apiResponse.status === 1) {
      const newRecords = apiResponse.data.records;
      console.log('Fetched records:', newRecords.length);
      
      // 使用空数组强制替换/追加，确保Vue能检测到变化
      if (isLoadMore) {
        // 加载更多，追加数据
        agreements.value = [...agreements.value, ...newRecords];
      } else {
        // 刷新数据，替换数据
        agreements.value = [...newRecords];
      }
      
      // 强制触发响应式更新
      agreements.value = [...agreements.value];
      
      total.value = apiResponse.data.total;
      console.log('Total records:', total.value);
      
      // 判断是否还有更多数据
      hasMore.value = agreements.value.length < apiResponse.data.total;
      console.log('Has more data:', hasMore.value);
      
      // 增加页码，为下次加载做准备
      pageNum.value++;
      console.log('Updated pageNum:', pageNum.value);
    } else {
      console.error('API Error:', apiResponse.msg);
      showToast(apiResponse.msg || '获取协议列表失败', 'error');
    }
  } catch (error) {
    console.error('获取协议列表异常:', error);
    showToast('获取协议列表异常，请重试', 'error');
  } finally {
    loading.value = false;
    loadingMore.value = false;
    console.log('Fetch completed, loading states reset');
  }
};

// 检查是否需要加载更多
const checkLoadMore = () => {
  if (!hasMore.value || loadingMore.value) return;
  
  // 获取滚动容器元素
  const scrollContainer = document.querySelector('.policy-list-content') as HTMLElement;
  if (!scrollContainer) return;
  
  const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
  
  // 调试信息
  console.log('Scroll check:', {
    scrollTop,
    scrollHeight,
    clientHeight,
    threshold: scrollHeight - 200,
    hasMore: hasMore.value,
    loading: loading.value,
    loadingMore: loadingMore.value
  });
  
  // 当滚动到距离底部200px时加载更多（更容易触发）
  const threshold = 200;
  if (scrollTop + clientHeight >= scrollHeight - threshold && hasMore.value && !loadingMore.value) {
    console.log('Loading more agreements...', { pageNum: pageNum.value });
    fetchAgreements(true);
  }
};

// 防抖处理的滚动检测
const debouncedCheckLoadMore = debounce(checkLoadMore, 200);

// 添加滚动监听器
const addScrollListener = () => {
  const scrollContainer = document.querySelector('.policy-list-content') as HTMLElement;
  if (scrollContainer) {
    scrollContainer.addEventListener('scroll', debouncedCheckLoadMore);
  }
};

// 移除滚动监听器
const removeScrollListener = () => {
  const scrollContainer = document.querySelector('.policy-list-content') as HTMLElement;
  if (scrollContainer) {
    scrollContainer.removeEventListener('scroll', debouncedCheckLoadMore);
  }
};

// 显示详情
const showContent = (agreement: Agreement) => {
  selectedAgreement.value = agreement;
  showDetail.value = true;
};

// 关闭详情
const closeDetail = () => {
  showDetail.value = false;
  selectedAgreement.value = null;
};

// 打开更新对话框
const openUpdateDialog = async (agreement: Agreement, newVersion: boolean) => {
  isNewVersion.value = newVersion;
  isAdding.value = false;
  editingAgreement.value = { ...agreement };
  showUpdateDialog.value = true;
  
  if (newVersion) {
    isLoadingContent.value = true;
    try {
      // 调用API获取新版本数据
      const responseStr = await invoke<string>('get_new_version_content', {
        id: agreement.id
      });
      const data = JSON.parse(responseStr);
      
      if (data.code === 200 && data.status === 1) {
        editingAgreement.value.content = data.data.content;
        editingAgreement.value.ver = data.data.ver
        editingAgreement.value.id = data.data.id;
        editingAgreement.value.type = data.data.type;
        editingAgreement.value.enabled = data.data.enabled;
        
      } else {
        showToast(`获取新版本内容失败：${data.msg || '未知错误'}`, 'error');
      }
    } catch (error) {
      console.error('获取新版本内容异常:', error);
      showToast(`获取新版本内容失败：${error instanceof Error ? error.message : '未知错误'}`, 'error');
    } finally {
      isLoadingContent.value = false;
    }
  }
};

// 打开新增对话框
const openAddDialog = () => {
  isAdding.value = true;
  isNewVersion.value = false;
  // 重置编辑协议对象
  editingAgreement.value = {
    id: '',
    type: '',
    content: '',
    ver: 1,
    enabled: 0,
    createdAt: '',
    createdBy: '',
    updatedAt: '',
    updatedBy: ''
  };
  showUpdateDialog.value = true;
};

// 关闭更新对话框
const closeUpdateDialog = () => {
  showUpdateDialog.value = false;
};

// 保存协议更新或新增
const saveAgreement = async () => {
  // 对于新增操作，验证协议类型和内容
  if (isAdding.value) {
    if (!editingAgreement.value.type) {
      showToast('请选择协议类型', 'error');
      return;
    }
    if (!editingAgreement.value.content.trim()) {
      showToast('请输入协议内容', 'error');
      return;
    }
  } else if (!editingAgreement.value.id) {
    return;
  }
  
  isSaving.value = true;
  try {
    // 根据是否为新增操作选择不同的API调用
    if (isAdding.value) {
      // 调用新增协议API
      const responseStr = await invoke<string>('add_new_agreement', {
        type: editingAgreement.value.type,
        content: editingAgreement.value.content
      });
      
      const apiResponse = JSON.parse(responseStr);
      
      if (apiResponse.code === 200 && apiResponse.status === 1) {
        showToast(`新增成功`, 'success');
        closeUpdateDialog();
        // 刷新协议列表
        await fetchAgreements(false);
      } else {
        console.error('新增协议失败:', apiResponse.msg);
        showToast(`新增失败：${apiResponse.msg || '未知错误'}`, 'error');
      }
    } else {
      // 调用更新协议API
      const responseStr = await invoke<string>('update_agreement', {
        id: editingAgreement.value.id,
        content: editingAgreement.value.content
      });
      
      const apiResponse = JSON.parse(responseStr);
      
      if (apiResponse.code === 200 && apiResponse.status === 1) {
        showToast(`更新成功`, 'success');
        closeUpdateDialog();
        // 刷新协议列表
        await fetchAgreements(false);
      } else {
        console.error('保存协议失败:', apiResponse.msg);
        showToast(`${isNewVersion.value ? '新版本创建' : '更新'}失败：${apiResponse.msg || '未知错误'}`, 'error');
      }
    }
  } catch (error) {
    console.error('保存协议异常:', error);
    showToast(`${isAdding.value ? '新增' : (isNewVersion.value ? '新版本创建' : '更新')}失败：${error instanceof Error ? error.message : '未知错误'}`, 'error');
  } finally {
    isSaving.value = false;
  }
};

// 截取内容预览
const truncateContent = (content: string, maxLength: number = 100): string => {
  if (!content) return '暂无内容';
  return content.length > maxLength ? content.substring(0, maxLength) + '...' : content;
};

// 显示提示消息
const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info', duration: number = 2000) => {
  if (window.showToast) {
    window.showToast?.(message, type, duration);
  } else {
    // 如果GlobalToast不可用，使用浏览器默认提示
    alert(message);
  }
};

// 切换协议状态
const toggleAgreementStatus = async (agreement: Agreement) => {
  // 避免重复点击
  if (updatingStatus.value.includes(agreement.id)) {
    return;
  }
  
  // 计算目标状态
  const targetEnabled = agreement.enabled ? 0 : 1;
  const targetStatusText = targetEnabled? '启用' : '禁用';
  
  try {
    // 添加到正在更新的列表中
    updatingStatus.value = [...updatingStatus.value, agreement.id];
    
    // 临时更新本地状态，提供即时反馈并确保enabled字段正确绑定
    const index = agreements.value.findIndex(a => a.id === agreement.id);
    if (index !== -1) {
      agreements.value[index] = {
        ...agreements.value[index],
        enabled: targetEnabled
      };
      // 强制触发响应式更新
      agreements.value = [...agreements.value];
    }
    
    // 通过Tauri调用Rust的API - 确保参数正确传递
    const responseStr = await invoke<string>('update_agreement_status', {
      id: agreement.id,
      enabled: targetEnabled + ''
    });
    
    // 处理响应数据
    const apiResponse = JSON.parse(responseStr);
    
    if (apiResponse.code === 200 && apiResponse.status === 1) {
      // 显示成功提示
      showToast(`协议已${targetStatusText}成功`, 'success');
      
      // 重新获取整个协议列表以刷新界面
      await fetchAgreements(false);
    } else {
      console.error('API Error:', apiResponse.msg);
      showToast(`${targetStatusText}失败：${apiResponse.msg || '未知错误'}`, 'error');
      // 如果API调用失败，恢复本地状态
      if (index !== -1) {
        agreements.value[index] = {
          ...agreements.value[index],
          enabled: agreement.enabled  // 恢复原始状态
        };
        agreements.value = [...agreements.value];
      }
    }
  } catch (error) {
    console.error('切换协议状态异常:', error);
    showToast(`切换状态失败：${error instanceof Error ? error.message : '未知错误'}`, 'error');
    // 如果发生异常，恢复本地状态
    const index = agreements.value.findIndex(a => a.id === agreement.id);
    if (index !== -1) {
      agreements.value[index] = {
        ...agreements.value[index],
        enabled: agreement.enabled  // 恢复原始状态
      };
      agreements.value = [...agreements.value];
    }
  } finally {
    // 从正在更新的列表中移除
    updatingStatus.value = updatingStatus.value.filter(id => id !== agreement.id);
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchAgreements();
  // 等待DOM渲染完成后添加滚动监听器
  nextTick(() => {
    addScrollListener();
  });
});

// 组件卸载时清理
onUnmounted(() => {
  removeScrollListener();
});
</script>

<style scoped>

/* 深灰+绿+白的配色方案 */
.policy-container {
  background-color: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 头部样式 - 独立于内容区域 */
.policy-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 20px;
  background-color: var(--bg-header);
  border-bottom: 1px solid var(--border);
  flex-wrap: wrap;
  flex-shrink: 0;
}

.policy-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-selection {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-select {
  padding: 8px 12px;
  background-color: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 6px;
  color: var(--text-primary);
  font-size: 14px;
  cursor: pointer;
}

.filter-select:focus {
  outline: none;
  border-color: var(--accent-primary);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.refresh-btn, .new-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  color: var(--text-inverse);
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.refresh-btn {
  background-color: var(--accent-primary);
}

.refresh-btn:hover {
  background-color: var(--accent-primary-hover);
}

.new-btn {
  background-color: var(--accent-info);
}

.new-btn:hover {
  background-color: var(--accent-info-hover);
}

/* 内容区域样式 - 独立滚动区域 */
.policy-list-content {
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 内容超出时显示垂直滚动条 */
  min-height: 400px; /* 设置最小高度，确保内容区域有足够空间 */
  max-height: calc(100vh - 180px); /* 最大高度不超过视口高度减去头部高度 */
  padding-bottom: 80px; /* 为底部加载提示留出空间 */
}

/* 滚动条样式 */
.policy-list-content::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.policy-list-content::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 4px;
}

.policy-list-content::-webkit-scrollbar-thumb {
  background: var(--border-hover);
  border-radius: 4px;
}

.policy-list-content::-webkit-scrollbar-thumb:hover {
  background: var(--accent-primary);
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  font-size: 16px;
  color: var(--text-secondary);
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  font-size: 16px;
  color: var(--text-secondary);
}

/* 协议列表 */
.agreement-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.agreement-item {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 20px;
  transition: border-color 0.3s ease;
}

.agreement-item:hover {
  border-color: var(--border-hover);
}

.agreement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.agreement-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.agreement-type {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.agreement-version {
  font-size: 14px;
  color: var(--text-secondary);
  background-color: var(--bg-tertiary);
  padding: 4px 8px;
  border-radius: 4px;
}

.agreement-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.enabled {
  background-color: var(--accent-success);
  color: var(--text-inverse);
}

.status-badge.disabled {
  background-color: var(--bg-disabled);
  color: var(--text-inverse);
}

.status-badge:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 为状态徽章添加按钮样式 */
.status-badge {
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  outline: none;
  font-family: inherit;
}

.status-badge:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: var(--shadow-hover);
}

.status-badge.enabled:hover:not(:disabled) {
  background-color: var(--accent-success-hover);
}

.status-badge.disabled:hover:not(:disabled) {
  background-color: var(--bg-disabled-hover);
}

.view-btn {
  padding: 6px 16px;
  background-color: transparent;
  border: 1px solid var(--accent-primary);
  border-radius: 6px;
  color: var(--accent-primary);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.view-btn:hover {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.agreement-info {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  gap: 6px;
  font-size: 14px;
}

.info-item .label {
  color: var(--text-secondary);
}

.info-item .value {
  color: var(--text-primary);
}

.agreement-preview {
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.6;
  word-break: break-word;
}

/* 加载更多指示器 */
.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  padding: 24px;
  color: var(--text-secondary);
  font-size: 14px;
}

.loading-spinner-small {
  width: 20px;
  height: 20px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 已加载全部数据提示 */
.load-complete {
  text-align: center;
  padding: 24px;
  color: var(--text-secondary);
  font-size: 14px;
}

/* 更新按钮样式 */
.update-btn {
  padding: 6px 16px;
  background-color: var(--accent-info);
  border: none;
  border-radius: 6px;
  color: var(--text-inverse);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.update-btn:hover {
  background-color: var(--accent-info-hover);
}

/* 新版本按钮样式 */
.new-version-btn {
  padding: 6px 16px;
  background-color: var(--accent-warning);
  border: none;
  border-radius: 6px;
  color: var(--text-inverse);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.new-version-btn:hover {
  background-color: var(--accent-warning-hover);
}

/* 详情弹窗 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--bg-overlay);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
}

.detail-content {
  background-color: var(--bg-card);
  border-radius: 12px;
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
}

.detail-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-primary);
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.close-btn:hover {
  background-color: var(--bg-tertiary);
}

.detail-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.detail-info {
  margin-bottom: 24px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-label {
  color: var(--text-secondary);
  min-width: 80px;
}

.info-value {
  color: var(--text-primary);
}

.info-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.info-status.enabled {
  background-color: var(--accent-success);
  color: var(--text-inverse);
}

.info-status.disabled {
  background-color: var(--bg-disabled);
  color: var(--text-inverse);
}

.detail-text h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 更新表单样式 */
.update-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  padding: 12px;
  background-color: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 6px;
  color: var(--text-primary);
  font-size: 14px;
  font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: var(--accent-primary);
}

.form-group textarea {
  resize: vertical;
  min-height: 200px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-btn {
  padding: 8px 20px;
  background-color: transparent;
  border: 1px solid var(--border);
  border-radius: 6px;
  color: var(--text-primary);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.cancel-btn:hover:not(:disabled) {
  background-color: var(--bg-tertiary);
}

.save-btn {
  padding: 8px 20px;
  background-color: var(--accent-primary);
  border: none;
  border-radius: 6px;
  color: var(--text-inverse);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.save-btn:hover:not(:disabled) {
  background-color: var(--accent-primary-hover);
}

.save-btn:disabled,
.cancel-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.content-display {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 20px;
  font-size: 14px;
  line-height: 1.8;
  color: var(--text-secondary);
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 400px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .policy-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-selection,
  .header-actions {
    justify-content: center;
  }
  
  .agreement-info {
    flex-direction: column;
    gap: 8px;
  }
  
  .pagination {
    flex-direction: column;
    gap: 16px;
  }
  
  .detail-modal {
    padding: 10px;
  }
  
  .detail-content {
    margin: 10px;
  }
}
</style>